const randomIntFromInterval = (min, max) =>  
  Math.floor(Math.random() * (max - min + 1) + min);  
  
const simulateBattle = (pokemonA, pokemonB) => {  
  // console.log(pokemonA);
  // console.log(pokemonB);
  
  const speedA = pokemonA.stats_speed;  
  // const speedB = JSON.parse(pokemonB.stats).Speed;  
  const speedB = pokemonB.stats.Speed;  
  let scoreA = 0;  
  let scoreB = 0;  
  
  for (let round = 0; round < 10; round++) {  
    let attacker, defender;  
    if (round % 2 === 0) {  
      speedA > speedB ? (attacker = pokemonA, defender = pokemonB) : (attacker = pokemonB, defender = pokemonA);  
    } else {  
      speedB > speedA ? (attacker = pokemonB, defender = pokemonA) : (attacker = pokemonA, defender = pokemonB);  
    }  
    // console.log(attacker,defender);
    
    // const attackTypes = JSON.parse(attacker.type);  
    const attackTypes = attacker.type;  
    // const weaknesses = JSON.parse(defender.weaknesses);  
    const weaknesses = defender.weaknesses;  
    let damageMultiplier = 1;  
  
    for (const type of attackTypes) {  
      if (weaknesses.includes(type)) {  
        damageMultiplier += randomIntFromInterval(0.01, 0.2); // 1% to 20% bonus damage  
        break;  
      }  
    }  
  
    // const attackPower = (attacker === pokemonA) ? pokemonA.stats_attack : JSON.parse(pokemonB.stats).Attack;  
    const attackPower = (attacker === pokemonA) ? pokemonA.stats_attack : pokemonB.stats.Attack;  
    // const defensePower = (defender === pokemonA) ? pokemonA.stats_defense : JSON.parse(pokemonB.stats).Defense;  
    const defensePower = (defender === pokemonA) ? pokemonA.stats_defense : pokemonB.stats.Defense;  
    if (attackPower * damageMultiplier > defensePower) {  
      (attacker === pokemonA) ? scoreA++ : scoreB++;  
    } else {  
      (defender === pokemonA) ? scoreA++ : scoreB++;  
    }  
  
    // const specialAttackPower = (attacker === pokemonA) ? pokemonA.stats_special_attack : JSON.parse(pokemonB.stats).Special_Attack;  
    const specialAttackPower = (attacker === pokemonA) ? pokemonA.stats_special_attack : pokemonB.stats.Special_Attack;  
    // const specialDefensePower = (defender === pokemonA) ? pokemonA.stats_special_defense : JSON.parse(pokemonB.stats).Special_Defense;  
    const specialDefensePower = (defender === pokemonA) ? pokemonA.stats_special_defense : pokemonB.stats.Special_Defense;  
    if (specialAttackPower * damageMultiplier > specialDefensePower) {  
      (attacker === pokemonA) ? scoreA++ : scoreB++;  
    } else {  
      (defender === pokemonA) ? scoreA++ : scoreB++;  
    }  
  }  
  
  return scoreA > scoreB ? pokemonA : pokemonB;  
};  
  
module.exports = simulateBattle;
/** 比赛规则
 *  1.一共进行10轮比拼，交替做进攻方，先用速度决定谁为第一轮进攻方，a的速度是a.stats_speed,b的速度是JSON.parse(b.stats).Speed
 2.判断攻击方type类型中是否含有防御方weaknesses中的弱点，如果有，普通攻击伤害增加随机1%～20%
	3.用进攻方的基础攻击对比防守方的基本防御
 4.用进攻方的特殊攻击对比防守方的特殊防御
 5.比拼10轮，谁胜的多，最后判断战斗结果，胜利一方
 */